package com.lipl.base.javaee.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Scattering:将数据写入到buffer时，可以采用buffer数组，依次写入[分组]
 * Gathering: 从buffer读取数据时，可以采用buffer数组，依次读
 */
public class ScatterAndGatheringTest {
    public static void main(String[] args) throws IOException {

        //使用 ServerSocketChannel 和 SocketChannel 网络

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        serverSocketChannel.socket().bind(inetSocketAddress);

        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等待客户端连接（telnet）
        SocketChannel socketChannel = serverSocketChannel.accept();
        int messageLength = 8;  //假定从客户端接口8个字节
        //循环的读取
        while(true){

            int byteRead = 0;

            while(byteRead < messageLength){
                long read = socketChannel.read(byteBuffers);
                byteRead += read;
                System.out.println("byteRead="+byteRead);
                //使用流打印
                Arrays.asList(byteBuffers).stream().map(byteBuffer -> "postion="
                + byteBuffer.position() +",limit="+ byteBuffer.limit()).forEach(System.out::println);

                Arrays.asList(byteBuffers).forEach(buffer->buffer.flip());

                //读出数据
                long byteWirte = 0;
                while (byteWirte < messageLength){
                    long write = socketChannel.write(byteBuffers);
                    byteWirte += write;
                }

                //将所有的buffer进行clear

                Arrays.asList(byteBuffers).forEach(buffer -> buffer.clear() );

                System.out.println("byteRead:=" +byteRead+"byteWrite="+byteWirte+",messagelength" + messageLength);
            }
        }

    }
}

